package bb.lanxing.lib.devices.core;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import androidx.core.content.ContextCompat;
import bb.lanxing.lib.devices.api.ConnectionListener;
import bb.lanxing.lib.devices.api.DeviceManager;
import bb.lanxing.lib.devices.api.DeviceStateListener;
import bb.lanxing.lib.devices.api.PeerDevice;
import bb.lanxing.lib.devices.api.SmartDevice;
import bb.lanxing.lib.devices.core.utils.ConnectionStateNotifier;
import bb.lanxing.lib.devices.core.utils.DeviceStateNotifier;
import bb.lanxing.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public abstract class AbstractDeviceManager implements DeviceManager, ConnectionListener, DeviceStateListener {
    private final Map<String, PeerDevice> mDevices = new HashMap<>();
    private final ConnectionStateNotifier mStateNotifier = new ConnectionStateNotifier();
    private final DeviceStateNotifier mDeviceStateNotifier = new DeviceStateNotifier();

    protected abstract PeerDevice createDeviceIfNeed(SmartDevice smartDevice);

    protected void d(String str) {
    }

    public abstract Context getContext();

    protected boolean isSupportedDevice(int i) {
        return false;
    }

    public static boolean checkBluetooth(Context context) {
        int checkSelfPermission;
        int checkSelfPermission2;
        BluetoothManager bluetoothManager;
        BluetoothAdapter adapter;
        if (Build.VERSION.SDK_INT >= 31) {
            checkSelfPermission = ContextCompat.checkSelfPermission(context, "android.permission.BLUETOOTH_SCAN");
            checkSelfPermission2 = ContextCompat.checkSelfPermission(context, "android.permission.BLUETOOTH_CONNECT");
        } else {
            checkSelfPermission = ContextCompat.checkSelfPermission(context, "android.permission.BLUETOOTH");
            checkSelfPermission2 = ContextCompat.checkSelfPermission(context, "android.permission.BLUETOOTH_ADMIN");
        }
        return (checkSelfPermission | checkSelfPermission2) == 0 && (bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE)) != null && (adapter = bluetoothManager.getAdapter()) != null && adapter.isEnabled();
    }

    public PeerDevice getDeviceByType(int i, int i2) {
        Iterator<Map.Entry<String, PeerDevice>> it = iterator();
        while (it.hasNext()) {
            PeerDevice value = it.next().getValue();
            if (value.getProtocol() == i && value.getType() == i2) {
                return value;
            }
        }
        return null;
    }

    public List<PeerDevice> getDevicesByType(int i, int i2) {
        Iterator<Map.Entry<String, PeerDevice>> it = iterator();
        ArrayList<PeerDevice> arrayList = new ArrayList<>();
        while (it.hasNext()) {
            PeerDevice value = it.next().getValue();
            if (value.getProtocol() == i && value.getType() == i2) {
                arrayList.add(value);
            }
        }
        return arrayList;
    }

    @Override
    public void removeDeviceByAddress(String str) {
        Iterator<Map.Entry<String, PeerDevice>> it = iterator();
        while (it.hasNext()) {
            if (str.equals(it.next().getValue().getAddress())) {
                it.remove();
                return;
            }
        }
    }

    public void addPeerDevice(PeerDevice peerDevice) {
        this.mDevices.put(peerDevice.getAddress(), peerDevice);
    }

    public List<PeerDevice> getMultiDevicesByType(int i) {
        ArrayList<PeerDevice> arrayList = new ArrayList<>();
        Iterator<Map.Entry<String, PeerDevice>> it = iterator();
        while (it.hasNext()) {
            PeerDevice value = it.next().getValue();
            if (value.getType() == i) {
                arrayList.add(value);
            }
        }
        return arrayList;
    }

    public List<PeerDevice> getConnectedDevicesByType(int i) {
        ArrayList<PeerDevice> arrayList = new ArrayList<>();
        Iterator<Map.Entry<String, PeerDevice>> it = iterator();
        while (it.hasNext()) {
            PeerDevice value = it.next().getValue();
            if (value.getType() == i && value.isConnected()) {
                arrayList.add(value);
            }
        }
        return arrayList;
    }

    public PeerDevice getDeviceByAddress(String deviceAddress) {
        if (TextUtils.isEmpty(deviceAddress)) {
           // Log.d("wangsm_bt", " getDeviceByAddress str is empty,retun null");
            return null;
        }
        Iterator<Map.Entry<String, PeerDevice>> it = iterator();
        while (it.hasNext()) {
            PeerDevice value = it.next().getValue();
            if (deviceAddress.equals(value.getAddress())) {
               // Log.d("wangsm_bt", " getDeviceByAddress finall,retun PeerDevice value");
                return value;
            }
        }
      //  Log.d("wangsm_bt", " getDeviceByAddress finall,retun null");
        return null;
    }

    @Override
    public PeerDevice getDevice(int i, int i2) {
        return getDeviceByType(i, i2);
    }

    @Override
    public List<PeerDevice> getDevices(int i, int i2) {
        return getDevicesByType(i, i2);
    }

    @Override
    public PeerDevice getDevice(String str) {
        return getDeviceByAddress(str);
    }

    @Override
    public void connect(SmartDevice smartDevice) {
        PeerDevice createDeviceIfNeed = createDeviceIfNeed(smartDevice);
        if (createDeviceIfNeed != null) {
            createDeviceIfNeed.connect();
        }
    }

    @Override
    public boolean isConnected(int deviceType) {
        List<PeerDevice> multiDevicesByType = getMultiDevicesByType(deviceType);
        if (!multiDevicesByType.isEmpty()) {
            for (PeerDevice peerDevice : multiDevicesByType) {
                if (peerDevice.isConnected()) {
                    return true;
                }
            }
            return false;
        }
        return false;
    }

    @Override
    public boolean isConnecting(String deviceAddress) {
        PeerDevice deviceByAddress = getDeviceByAddress(deviceAddress);
        if (deviceByAddress != null) {
            return deviceByAddress.isConnecting();
        }
        return false;
    }

    @Override
    public int getDeviceState(String deviceAddress) {
        PeerDevice deviceByAddress = getDeviceByAddress(deviceAddress);
        if (deviceByAddress != null) {
            return deviceByAddress.getDeviceState();
        }
        return PeerDevice.STATE_DEVICE_STATE_FREE;
    }

    @Override
    public boolean isConnected(String deviceAddress) {
        PeerDevice deviceByAddress = getDeviceByAddress(deviceAddress);
        return deviceByAddress != null && deviceByAddress.isConnected();
    }

    @Override
    public void disconnect(int deviceType) {
        List<PeerDevice> multiDevicesByType = getMultiDevicesByType(deviceType);
        if (!multiDevicesByType.isEmpty()) {
            for (PeerDevice peerDevice : multiDevicesByType) {
                peerDevice.close();
            }
        }
    }

    @Override
    public void disconnect(String deviceAddress) {
        PeerDevice deviceByAddress = getDeviceByAddress(deviceAddress);
        if (deviceByAddress != null) {
            deviceByAddress.setDisConnectFromUser(true);
//            deviceByAddress.disconnect();//deviceByAddress.close() will call disconnect()
            deviceByAddress.close();
            removeDeviceByAddress(deviceAddress);
        }
    }

    @Override
    public void disconnectAll() {
        Iterator<Map.Entry<String, PeerDevice>> it = iterator();
        while (it.hasNext()) {
            it.next().getValue().close();
        }
    }

    public void onConnectionStateChanged(SmartDevice smartDevice, int i, int i2) {
        notifyStateChanged(smartDevice, i, i2);
    }

    @Override
    public void registerConnectionStateListener(ConnectionListener connectionListener) {
        this.mStateNotifier.registerConnectionListener(connectionListener);
    }

    @Override
    public void unregisterConnectionStateListener(ConnectionListener connectionListener) {
        this.mStateNotifier.unregisterConnectionListener(connectionListener);
    }

    @Override
    public void registerDeviceStateListener(DeviceStateListener deviceStateListener) {
        this.mDeviceStateNotifier.registerDeviceStateListener(deviceStateListener);
    }

    @Override
    public void unregisterDeviceStateListener(DeviceStateListener deviceStateListener) {
        this.mDeviceStateNotifier.unregisterDeviceStateListener(deviceStateListener);
    }

    public void notifyStateChanged(SmartDevice smartDevice, int i, int i2) {
        this.mStateNotifier.notifyStateChanged(smartDevice, i, i2);
    }

    public ConnectionStateNotifier getConnectionStateNotifier() {
        return this.mStateNotifier;
    }

    protected void notifyDeviceStateChanged(SmartDevice smartDevice, int i) {
        this.mDeviceStateNotifier.notifyStateChanged(smartDevice, i);
    }

    @Override
    public void onDeviceStateChanged(SmartDevice smartDevice, int i) {
        notifyDeviceStateChanged(smartDevice, i);
    }

    protected Iterator<Map.Entry<String, PeerDevice>> iterator() {
        return this.mDevices.entrySet().iterator();
    }

    protected DeviceStateNotifier getDeviceStateNotifier() {
        return this.mDeviceStateNotifier;
    }

    @Override
    public void release() {
        Iterator<Map.Entry<String, PeerDevice>> it = iterator();
        while (it.hasNext()) {
            it.next().getValue().close();
        }
        this.mDevices.clear();
    }
}
